package com.yt.al.main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.yt.al.db.HuaFeiDao;
import com.yt.al.db.PhoneDao;
import com.yt.al.db.RunDao;
import com.yt.al.db.SmsDao;
import com.yt.al.service.SWGJService;
import com.yt.al.service.ZSYYTService;
import com.yt.al.util.ConfigUtil;
import com.yt.al.util.WriteLogUtil;

public class ProgramMain {
	public static int maxErrCount = 3;
	public static int curErrCount = 0;
	
	public static void errHandler(String errMsg)
	{
		curErrCount ++;
		if(curErrCount>=maxErrCount)
		{
			SmsDao sms = new SmsDao();
			sms.sendSms(errMsg);
			curErrCount = 0;
			maxErrCount += 3;
		}
	}
	
	public static void resumeErr()
	{
		maxErrCount = 3;
		curErrCount = 0;
	}
	
	public static String getIP()
	{
		try {
			InetAddress ia = InetAddress.getLocalHost();
			String ip = ia.getHostAddress();
			return ip;
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return "";
		
	}

	public static void main(String[] args) {
		
//		SmsDao sms = new SmsDao();
//		sms.sendSms("出现故障");

		Timer timer = new Timer();

		HuaFeiTask task = new HuaFeiTask();

		task.running = true;
		timer.schedule(task, 1000, 60000);

		WriteLogUtil.writeMsgToFile("程序开始运行");
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					System.in));
			String inputStr = br.readLine();
			while (!inputStr.equals("exit")) {
				if (inputStr.equals("c")) {
					task.running = false;
					task.quit();

					System.exit(0);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

//		 ZSYYTService swgjService = new ZSYYTService("", "");
//		 swgjService.firstLogin("15838330528", "150602");
//		
//		 swgjService.quit();

	}
}

class MyTask extends TimerTask {

	ZSYYTService zsyytService = null;
	SWGJService swgjService = null;
	boolean running = false;

	int[] runTime = { 0, 0 };

	public int[] getRunTime() {
		return runTime;
	}

	public void setRunTime(int[] runTime) {
		this.runTime = runTime;
	}

	@Override
	public void run() {
		if(!running)
		{
			return;
		}
		String phoneAndPwd = "";
		String phoneId = "";
		String phone = "";
		String pwd = "";

		String url = ConfigUtil.getProperties("url");
		String udid = ConfigUtil.getProperties("udid");
		try {
			if (!canRunning()) {
				WriteLogUtil.writeMsgToFile("不在运行时间段");
				return;
			}
			PhoneDao phoneDao = new PhoneDao();
			String appNames = ConfigUtil.getProperties("app");
			if ("".equals(appNames)) {
				WriteLogUtil.writeMsgToFile("配置文件缺失");
				return;
			}
			String[] appStrs = appNames.split(",");

			List<String> appList = new ArrayList<String>();
			for (int j = 0; j < appStrs.length; j++) {
				appList.add(appStrs[j]);
			}

			for (int i = 0; i < appList.size(); i++) {
				String appName = appList.get(i);
				WriteLogUtil.writeMsgToFile("当前需处理的应用名称：" + appName);
				phoneAndPwd = phoneDao.phoneAndPwd(appName);
				boolean bFirst = true;
				boolean bAgain = false;

				while (!"".equals(phoneAndPwd)) {
					if (!canRunning()) {
						WriteLogUtil.writeMsgToFile("不在运行时间段");
						phoneDao.updatePhone(phoneId, phone, 0);
						return;
					}
					try {
						WriteLogUtil.writeMsgToFile("获取到号码数据：" + phoneAndPwd);
						String[] strs = phoneAndPwd.split(",");
						phone = strs[0];
						pwd = strs[1];
						phoneId = strs[2];
						int rel = 0;
						if (appName.equals("zsyyt")) {
							if (zsyytService == null) {
								zsyytService = new ZSYYTService(url, udid);
							}
							if (zsyytService.getDriver() == null) {
								String errMsg = "初始化错误，请及时处理。模块：zsyyt,主机："+ProgramMain.getIP()
										+",维护id:"+ConfigUtil.getProperties("alert");
								ProgramMain.errHandler(errMsg);
								WriteLogUtil.writeMsgToFile("初始化适配器失败，等待30秒后重试");
								phoneDao.updatePhone(phoneId, phone, 0);
								Thread.sleep(30000);
								return;
							}
							if (bFirst) {
								bFirst = false;
								if (bAgain) {
									WriteLogUtil.writeMsgToFile("首次再次登录");
									rel = zsyytService.firstAgainLogin(phone,
											pwd);
								} else {
									WriteLogUtil.writeMsgToFile("首次登录");
									rel = zsyytService.firstLogin(phone, pwd);
								}
								if (rel == 2) {
									bAgain = true;
									bFirst = true;
								} else {
									bAgain = false;
								}
							} else {
								if (bAgain) {
									WriteLogUtil.writeMsgToFile("二次再次登录");
									rel = zsyytService.secondAgainLogin(phone,
											pwd);
								} else {
									WriteLogUtil.writeMsgToFile("二次登录");
									rel = zsyytService.secondLogin(phone, pwd);
								}

								if (rel == 2) {
									bAgain = true;
								} else {
									bAgain = false;
								}
							}
						}
						if (appName.equals("swgj")) {
							if (swgjService == null) {
								swgjService = new SWGJService(url, udid);
							}
							if (swgjService.getDriver() == null) {
								String errMsg = "初始化错误，请及时处理。模块：swgj,主机："+ProgramMain.getIP()
										+",维护id:"+ConfigUtil.getProperties("alert");
								ProgramMain.errHandler(errMsg);
								WriteLogUtil.writeMsgToFile("初始化适配器失败，等待70秒后重试");
								phoneDao.updatePhone(phoneId, phone, 0);
								Thread.sleep(70000);
								return;
							}
							if (bFirst) {
								bFirst = false;
								if (bAgain) {
									WriteLogUtil.writeMsgToFile("首次再次登录");
									rel = swgjService.firstAgainLogin(phone,
											pwd);
								} else {
									WriteLogUtil.writeMsgToFile("首次登录");
									rel = swgjService.firstLogin(phone, pwd);
								}
								if (rel == 2) {
									bAgain = true;
									bFirst = true;
								} else {
									bAgain = false;
								}
							} else {
								if (bAgain) {
									WriteLogUtil.writeMsgToFile("二次再次登录");
									rel = swgjService.firstAgainLogin(phone,
											pwd);
								} else {
									WriteLogUtil.writeMsgToFile("二次登录");
									rel = swgjService.secondLogin(phone, pwd);
								}

								if (rel == 2) {
									bAgain = true;
								} else {
									bAgain = false;
								}
							}

						}

						if (rel == 0) {
							if (swgjService != null) {
								swgjService.quit();
								swgjService = null;

								bAgain = false;
								bFirst = true;
							}
							if (zsyytService != null) {
								zsyytService.quit();
								zsyytService = null;

								bAgain = false;
								bFirst = true;
							}
						}
						WriteLogUtil.writeMsgToFile("更新状态为：" + rel);
						phoneDao.updatePhone(phoneId, phone, rel);
						phoneAndPwd = phoneDao.phoneAndPwd(appName);

					} catch (Exception e) {
						if (!phoneId.equals("")) {
							WriteLogUtil.writeMsgToFile("操作异常，更新状态为：0");
							phoneDao.updatePhone(phoneId, phone, 0);
						}
						e.printStackTrace();
						if (zsyytService != null) {
							zsyytService.quit();
							zsyytService = null;
						}
						if (swgjService != null) {
							swgjService.quit();
							swgjService = null;
						}

						break;
					}

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (zsyytService != null) {
				zsyytService.quit();
				zsyytService = null;
			}
			if (swgjService != null) {
				swgjService.quit();
				swgjService = null;
			}
		}
	}

	public void quit() {
		if (zsyytService != null) {
			zsyytService.quit();
			zsyytService = null;
		}
		if (swgjService != null) {
			swgjService.quit();
			swgjService = null;
		}
	}
	
	
	

	public boolean canRunning() {
		RunDao runDao = new RunDao();
		runTime = runDao.getRunTime();
		int startHour = runTime[0];
		int endHour = runTime[1];
		Date d = new Date();
		int hours = d.getHours();
		if (hours >= startHour) {
			if (hours <= endHour) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}

	}
	
	
	
}

class HuaFeiTask extends TimerTask {

	ZSYYTService zsyytService = null;
	SWGJService swgjService = null;
	boolean running = false;

	int[] runTime = { 0, 0 };

	public int[] getRunTime() {
		return runTime;
	}

	public void setRunTime(int[] runTime) {
		this.runTime = runTime;
	}

	@Override
	public void run() {
		String phoneAndPwd = "";
		String phone = "";
		String pwd = "";

		String url = ConfigUtil.getProperties("url");
		String udid = ConfigUtil.getProperties("udid");
		try {
			HuaFeiDao phoneDao = new HuaFeiDao();
			phoneAndPwd = phoneDao.phoneAndPwd();
			boolean bFirst = true;
			boolean bAgain = false;

			while (!"".equals(phoneAndPwd)) {
				String huafei = "";
				try {
					WriteLogUtil.writeMsgToFile("获取到号码数据：" + phoneAndPwd);
					String[] strs = phoneAndPwd.split(",");
					phone = strs[0];
					pwd = strs[1];
					int rel = 0;
					if (zsyytService == null) {
						zsyytService = new ZSYYTService(url, udid);
					}
					if (zsyytService.getDriver() == null) {
						String errMsg = "初始化错误，请及时处理。模块：zsyyt,主机："+ProgramMain.getIP()
								+",维护id:"+ConfigUtil.getProperties("alert");
						ProgramMain.errHandler(errMsg);
						WriteLogUtil.writeMsgToFile("初始化适配器失败，等待30秒后重试");
						Thread.sleep(30000);
						return;
					}
					if (bFirst) {
						bFirst = false;
						if (bAgain) {
							WriteLogUtil.writeMsgToFile("话费查询，首次再次登录");
							huafei = zsyytService.huaFeiAgainLogin(phone,
									pwd);
						} else {
							WriteLogUtil.writeMsgToFile("话费查询，首次登录");
							huafei = zsyytService.huaFeiFirstLogin(phone, pwd);
						}
						if (huafei.equals("登录失败")) {
							bAgain = true;
							bFirst = true;
						} else {
							bAgain = false;
						}
					} else {
						if (bAgain) {
							WriteLogUtil.writeMsgToFile("话费查询，二次再次登录");
							huafei = zsyytService.huaFeiAgainLogin(phone,
									pwd);
						} else {
							WriteLogUtil.writeMsgToFile("话费查询，二次登录");
							huafei = zsyytService.huaFeiSecondLogin(phone, pwd);
						}

						if (huafei.equals("登录失败")) {
							bAgain = true;
						} else {
							bAgain = false;
						}
					}

				if (huafei.equals("-1")) {
					if (zsyytService != null) {
						zsyytService.quit();
						zsyytService = null;

						bAgain = false;
						bFirst = true;
					}
				}
				if(huafei.equals("")){
					phoneDao.updateHuaFeiFail(phone);
				}
				else{
					phoneDao.updateHuaFeiSuc(phone, huafei);
				}
				
				phoneAndPwd = phoneDao.phoneAndPwd();

				} catch (Exception e) {
					WriteLogUtil.writeMsgToFile("操作异常，更新状态为：0");
					e.printStackTrace();
					if (zsyytService != null) {
						zsyytService.quit();
						zsyytService = null;
					}
					break;
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (zsyytService != null) {
				zsyytService.quit();
				zsyytService = null;
			}
		}
	}

	public void quit() {
		if (zsyytService != null) {
			zsyytService.quit();
			zsyytService = null;
		}
		if (swgjService != null) {
			swgjService.quit();
			swgjService = null;
		}
	}
}


